package com.lkd.handler;
import com.google.common.collect.Lists;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.StatusInfo;
import com.lkd.contract.VmStatusContract;
import com.lkd.emq.Topic;
import com.lkd.exception.LogicException;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

@Component
@Topic(TopicConfig.VMS_STATUS_TOPIC)
@Slf4j
public class VMStatusHandler implements MsgHandler {

    @Autowired
    private TaskService taskService;
    @Autowired
    private VMService vmService;

    @Override
    public void process(String jsonMsg) throws IOException {
        log.info("自动创建工单");
        try {
            VmStatusContract vmStatusContract = JsonUtil.getByJson(jsonMsg, VmStatusContract.class);
            if (vmStatusContract==null || vmStatusContract.getStatusInfo()==null ||vmStatusContract.getStatusInfo().size()<=0) return;
            if(vmStatusContract.getStatusInfo().stream().anyMatch(s->s.isStatus() ==false)){
                VmVO vmInfo = vmService.getVMInfo(vmStatusContract.getInnerCode());
                if (vmInfo ==null){
                    return;
                }

                int userId = taskService.getLeastUser(vmInfo.getRegionId(), true);
                if (userId!=0){
                    TaskViewModel taskViewModel = new TaskViewModel();
                    taskViewModel.setCreateType(0);
                    taskViewModel.setInnerCode(vmStatusContract.getInnerCode());
                    taskViewModel.setUserId(userId);
                    taskViewModel.setAssignorId(0);
                    taskViewModel.setProductType(VMSystem.TASK_TYPE_REPAIR);
                    taskViewModel.setDesc(jsonMsg);
                    taskViewModel.setDetails(Lists.newArrayList());
                    taskService.createTask(taskViewModel);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("自动创建工单失败");
        }


    }
}
